import { defineComponent, reactive, ref, computed, onMounted, onUnmounted } from "vue";
import Page from "@/components/public/page/page";
import { CardWithTitle } from "@/components/public/card/card";
import LTable from "@/components/public/lTable/lTable";
import groupOrderEntryService from "@/modules/groupOrderManagement/groupOrderEntry.service";
import useNavigator from "@/hooks/useNavigator";
import { useStore as useUserStore } from "@/store/user";
import Add from "./popup/add"
import Voucher from "./popup/voucher/voucher";
import { message, Modal } from "ant-design-vue";
import { $groupOrderPeople, $groupOrderExportData } from "@/api/groupOrder/groupOrder";
import { useRouter } from "vue-router";
import eventBus from "@/common/mitt";

export default defineComponent({
  name: "groupOrderEntryPage",
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    const navigator = useNavigator();
    const addRef = ref(null as any);
    const voucherRef = ref(null as any);
    const visible = ref(false);
    const numberProgress = ref(0);
    const state = reactive({
      toolbar: {
        left: ["refresh", (!userStore.isSuperAdmin && userStore.channel_level > 2) && "groupAdd"],
        right: ["filter", "search"],
        groupAdd: {
          handler: () => {
            router.push("/groupOrderManagement/groupOrderEntryImportPage")
          }
        },
      },
      dataSource: [],
      columns: [
        {
          title: "ID",
          dataIndex: "id",
          align: "center",
          width: "80px",
        },
        {
          title: "系统订单号",
          dataIndex: "order_no",
          align: "center",
          width: "100px",
        },
        {
          title: "投保单位名称",
          dataIndex: "applicant_name",
          align: "center",
          width: "180px",
        },
        // {
        //   title: "投保单位证件号",
        //   dataIndex: "applicant_id_no",
        //   align: "center",
        //   width: "120px",
        // },
        {
          title: "联系人姓名",
          dataIndex: "contact_name",
          align: "center",
          width: "100px",
        },
        {
          title: "联系电话",
          dataIndex: "applicant_mobile",
          align: "center",
          width: "100px",
        },
        {
          title: "参保人数",
          dataIndex: "people_count",
          align: "center",
          width: "80px",
        },
        {
          title: "总金额",
          dataIndex: "sum_premium",
          align: "center",
          width: "80px",
        },
        {
          title: "状态",
          dataIndex: ["order_status", "label"],
          align: "center",
          width: "100px",
        },
        {
          title: "上传时间",
          dataIndex: "create_time",
          align: "center",
          width: "180px",
        },
        {
          fixed: "right",
          title: "操作",
          dataIndex: "operation",
          align: "center",
          width: "200px",
        },
      ],
      loading: false,
      searchForm: {
        contact_name: {
          type: "input",
          label: "联系人姓名",
          attrs: { placeholder: "请输入联系人姓名" },
        },
        insure_id_no: {
          type: "input",
          label: "被保人证件号",
          attrs: { placeholder: "请输入被保人证件号" },
        },
        order_status: {
          type: "select",
          label: "状态",
          attrs: { placeholder: "请选择状态" },
          datas: [
            { label: "凭证待上传", value: 0 },
            { label: "凭证待确认", value: 10 },
            { label: "确认失败", value: 12 },
            { label: "已取消", value: 1000 },
            { label: "待承保", value: 11 },
          ],
        },
      },
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
    } as any);
    // 表格状态变更
    const tableChangeHandler = (pag: { pageSize: number; current: number }) => {
      state.pagination.current = pag.current;
      state.pagination.pageSize = pag.pageSize;
    };
    // 选中项变更
    const onSelectChange = (changableRowKeys: any[]) => {
      state.selectedRowKeys = changableRowKeys;
    };
    const rowSelection = computed(() => {
      return {
        selectedRowKeys: state.selectedRowKeys,
        fixed: true,
        onChange: onSelectChange,
      };
    });
    // 服务
    const $service = new groupOrderEntryService();
    // 表格节点
    const LTableRef = ref(null as any);
    const DetailRef = ref(null as any);
    const tableRow = () => {
      LTableRef.value.$fetchTableData();
    };
    const deleteRow = (id: string | number) => {
      Modal.confirm({
        title: "提示",
        content: "确认取消?",
        onOk: () => {
          $service.delete({
            order_no: id,
          }).then((res: any) => {
            LTableRef.value.$fetchTableData();
          });
        },
      });
    }
    const exportData = (e: any) => {
      $groupOrderExportData({
        order_no: navigator?.route?.query?.order_no,
        number: e,
      }).then((res: any) => {
        numberProgress.value = (res?.data?.finish || 0) / (res?.data?.total || 0) * 100;
        if (res?.data?.status === 1) {
          window.open(res.data.url);
        }
        else if (res?.data?.status === 10) {
          exportData(e);
        }
        else if (res?.data?.status === -1) {
          visible.value = false;
          message.error("导出清单失败,请联系技术人员")
        }
      })
    }
    onMounted(() => {
      eventBus.groupOrderEntryImportConfirm.on(() => {
        tableRow();
      })
    })
    onUnmounted(() => {
      eventBus.groupOrderEntryImportConfirm.off();
    })
    return () => (
      <Page>
        <CardWithTitle title="团单录入">
          <LTable
            ref={LTableRef}
            service={$service}
            toolbar={state.toolbar}
            v-model={state}
          >
            <a-table
              bordered={true}
              scroll={{ x: "max-content" }}
              dataSource={state.dataSource}
              columns={state.columns}
              pagination={state.pagination}
              onChange={tableChangeHandler}
              //row-selection={rowSelection.value}
              loading={state.loading}
              rowKey="id"
              v-slots={{
                bodyCell: ({ column, record }: any) => {
                  // // 操作栏
                  if (column.dataIndex === "operation") {
                    return (
                      <div class="operation">
                        {
                          (record.order_status.value == 0 || record.order_status.value == 12) && (
                            <a-button
                              type="primary"
                              size="small"
                              onClick={() => {
                                voucherRef.value.open(record.order_no, record.order_status.value);
                              }}
                            >
                              上传凭证
                            </a-button>
                          )
                        }
                        {
                          (record.order_status.value == 10 || record.order_status.value == 11) && (
                            <a-button
                              type="primary"
                              size="small"
                              onClick={() => {
                                voucherRef.value.open(record.order_no, record.order_status.value);
                              }}
                            >
                              查看凭证
                            </a-button>
                          )
                        }
                        <a-button
                          type="primary"
                          size="small"
                          onClick={() => {
                            navigator.push({
                              path: "/groupOrderManagement/groupOrderEntryDetailPage",
                              query: {
                                order_no: record.order_no,
                              },
                            });
                          }}
                        >
                          查看清单
                        </a-button>
                        {/* <a-button
                              type="primary"
                              size="small"
                              onClick={() => {
                                $groupOrderPeople({order_no: record.order_no}).then((res:any)=>{
                                  $groupOrderExportData({
                                    order_no:record.order_no,
                                    number:res?.data?.number,
                                  }).then((res:any)=>{
                                  })
                                  numberProgress.value = 0;
                                  visible.value = true;
                                  exportData(res?.data?.number);
                    
                                 })
                              }}
                            >
                              下载清单
                            </a-button> */}
                        {
                          (record.order_status.value == 0 || record.order_status.value == 10 ||
                            record.order_status.value == 12
                          ) && (
                            <a-button
                              type="primary"
                              size="small"
                              danger
                              onClick={() => deleteRow(record.order_no)}
                            >
                              取消团单
                            </a-button>
                          )
                        }
                      </div>
                    );
                  }
                },
              }}
            />
          </LTable>
        </CardWithTitle>
        {
          <a-modal v-model:visible={visible.value} width="1000px" title="清单下载进度" closable={false}
            maskClosable={false}
            ok-button-props={{ disabled: (numberProgress.value == 100 ? false : true) }}
            cancel-button-props={{ disabled: (numberProgress.value == 100 ? false : true) }}
            onOk={() => {
              visible.value = false;
            }}
            cancel={() => {
              visible.value = false;
            }}
          >
            <a-progress percent={numberProgress.value} />
          </a-modal>
        }
        {/* <Add
          ref={addRef}
          onConfirm={(e) => {
            tableRow(e);
          }}
        /> */}
        <Voucher
          ref={voucherRef}
          onConfirm={() => {
            tableRow();
          }}
        />
      </Page>
    );
  },
});